import { defineComponent, onMounted, onUnmounted, ref } from 'vue'
import {
  addResizeListener,
  removeResizeListener,
} from 'amtf/utils/resize-event'

export default defineComponent({
  name: 'vue-dom-resize-observer',
  props: {
    tagName: {
      type: String,
      required: true,
    },
    id: {
      type: [String, Number],
      default: null,
    },
  },
  setup(props, { emit, slots }) {
    const resizeListener = (contentRect) => {
      const { left, top, width, height } = contentRect
      // emit('on-dom-resize-change', {
      emit('dom-resize-change', {
        key: props.id,
        left,
        top,
        width,
        height,
      })
    }

    const elementRef = ref(null)

    onMounted(() => {
      // console.log(`elementRef 👉`, elementRef)
      addResizeListener(elementRef.value, resizeListener)
    })

    onUnmounted(() => {
      removeResizeListener(elementRef.value, resizeListener)
    })

    return () => (
      <props.tagName ref={elementRef}>{slots.default?.()}</props.tagName>
    )
  },
})
